<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/14
 * Time: 15:54
 */
/**
 * 请求接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $params [请求的参数]
 * @param  int $ipost [是否采用POST形式]
 * @return  string
 */
function juhecurl($url, $params = false, $ispost = 0)
{
    $httpInfo = array();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22');
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    if ($ispost) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_URL, $url);
    } else {
        if ($params) {
            curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
        } else {
            curl_setopt($ch, CURLOPT_URL, $url);
        }
    }
    $response = curl_exec($ch);
    if ($response === FALSE) {
        //echo "cURL Error: " . curl_error($ch);
        return false;
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
    curl_close($ch);
    return $response;
}
/*
    ***聚合数据（JUHE.CN）短信API服务接口PHP请求示例源码
    ***DATE:2015-05-25
*/
function code($mobile,$code)
{

    header('content-type:text/html;charset=utf-8');

    $sendUrl = 'http://v.juhe.cn/sms/send'; //短信接口的URL

    $smsConf = array(
        'key' => '4df8a1c6fdba00d511a08d58aac8b3d8', //您申请的APPKEY
        'mobile' => $mobile, //接受短信的用户手机号码
        'tpl_id' => '52840', //您申请的短信模板ID，根据实际情况修改
        'tpl_value' => "#code#={$code}&#company#=聚合数据" //您设置的模板变量，根据实际情况修改
    );

    $content =juhecurl($sendUrl, $smsConf, 1); //请求发送短信

    if ($content) {
        $result = json_decode($content, true);
        $error_code = $result['error_code'];
        if ($error_code == 0) {
            //状态为0，说明短信发送成功
            echo "短信发送成功,短信ID：" . $result['result']['sid'];
        } else {
            //状态非0，说明失败
            $msg = $result['reason'];
            echo "短信发送失败(" . $error_code . ")：" . $msg;
        }
    } else {
        //返回内容异常，以下可根据业务逻辑自行修改
        echo "请求发送短信失败";
    }
}


/**
 * 验证身份证号是否合法
 *
 * @param string $identity 待验证的身份证号
 * @return bool
 */
function validate_identity($identity)
{
    //判断证号位数
    if (!preg_match("/(\\d{18})|(\\d{17}(\\d|X|x))/i", $identity))
    {
        return false;
    }

    //每位数对应的乘数因子
    $factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];

    //计算身份证号前17位的和
    $sum = 0;
    for ($index = 0; $index < 17; ++$index)
    {
        $sum += $factors[$index] * intval(substr($identity, $index, 1));
    }

    //将和对11取余
    $mod = $sum % 11;
    //最后一位字符
    $lastLetter = substr($identity, -1, 1);

    //根据获得的余数，获取验证码
    switch ($mod)
    {
        case 0:
            return $lastLetter == 1;
        case 1:
            return $lastLetter == 0;
        case 2:
            return strtoupper($lastLetter) == "X";
        default:
            return $lastLetter == 12 -$mod;
    }
}

/**
 * 将数据先转换成json,然后转成array
 */
function json_array($result){
    $result_json = json_encode($result);
    return json_decode($result_json,true);
}

/**
 * 向所有设备推送消息
 * @param string $message 需要推送的消息
 */
function sendNotifyAll($message){
    require_once "JPush\JPush.php";
    $app_key = 'your app_key';                //填入你的app_key
    $master_secret = 'your master_secret';    //填入你的master_secret
    $client = new \JPush($app_key,$master_secret);
    $result = $client->push()->setPlatform('all')->addAllAudience()->setNotificationAlert($message)->send();
    return json_array($result);
}


/**
 * 向特定设备推送消息
 * @param array $regid 特定设备的设备标识
 * @param string $message 需要推送的消息
 */
function sendNotifySpecial($regid,$message){
    require_once "JPush\JPush.php";
    $app_key = 'your app_key';                //填入你的app_key
    $master_secret = 'your master_secret';    //填入你的master_secret
    $client = new \JPush($app_key,$master_secret);
    $result = $client->push()->setPlatform('all')->addRegistrationId($regid)->setNotificationAlert($message)->send();
    return json_array($result);
}

/**
 * 向指定设备推送自定义消息
 * @param string $message 发送消息内容
 * @param array $regid 特定设备的id
 * @param int $did 状态值1
 * @param int $mid 状态值2
 */

function sendSpecialMsg($regid,$message,$did,$mid){
    require_once "JPush\JPush.php";
    $app_key = 'your app_key';                //填入你的app_key
    $master_secret = 'your master_secret';    //填入你的master_secret
    $client = new \JPush($app_key,$master_secret);
    $result = $client->push()->setPlatform('all')->addRegistrationId($regid)
        ->addAndroidNotification($message,'',1,array('did'=>$did,'mid'=>$mid))
        ->addIosNotification($message,'','+1',true,'',array('did'=>$did,'mid'=>$mid))->send();

    return json_array($result);
}

/**
 * 得到各类统计数据
 * @param array $msgIds 推送消息返回的msg_id列表
 */
function reportNotify($msgIds){
    require_once "JPush\JPush.php";
    $app_key = 'your app_key';                //填入你的app_key
    $master_secret = 'your master_secret';    //填入你的master_secret
    $client = new \JPush($app_key,$master_secret);
    $response = $client->report()->getReceived($msgIds);
    return json_array($response);
}

/*
 * 图片上传
 *
 * */

function uploadImg() {
    $result = array( 'status' => 1, 'msg' => '上传完成');
    if(trim($_FILES['file']['name']) != ''){
        //判断上传根目录是否存在
        if(!is_dir(C('PICTURE_UPLOAD')['rootPath'])) {
            mkdir(C('PICTURE_UPLOAD')['rootPath'], 0777, true);
        }

        $upload = new \Think\Upload(C('PICTURE_UPLOAD')); // 实例化上传类
        $upload->replace  = true; //覆盖

        // 上传文件
        $info = $upload->uploadOne($_FILES['file']);
        if(!$info) {
            $result = array( 'status' => 0, 'msg' => $upload->getError() );
        }else{
            $result['src'] = C('UPLOAD_PICTURE_ROOT') . '/' . $info['savepath'] . $info['savename'];
        }
    } else {
        $result = ['status' => 0, 'msg' => '上传失败'];
    }

    return $result;
}

/**
 * 商品价格转换 分-》元
 * @param $fen
 * @return string
 */
function fen_to_yuan($fen) {
    return sprintf('%.2f', $fen / 100.00);
}

/**
 * 价格转换 元-》分
 * @param $yuan
 * @return mixed
 */
function yuan_to_fen($yuan) {
    return $yuan * 100;
}


/**
 * 获取随机位数数字
 * @param integer $len 长度
 * @return string
 */
function randNumber($len = 4){
    $chars = str_repeat('0123456789', 10);
    $chars = str_shuffle($chars);
    $str = substr($chars, 0, $len);
    return $str;
}

function uploadFile() {
    $result = array( 'status' => 1, 'msg' => '上传完成');
    if(trim($_FILES['file']['name']) != ''){
        //判断上传根目录是否存在
        if(!is_dir(C('FIELD_UPLOAD')['rootPath'])) {
            mkdir(C('FIELD_UPLOAD')['rootPath'], 0777, true);
        }

        $upload = new \Think\Upload(C('FIELD_UPLOAD')); // 实例化上传类
        $upload->replace  = true; //覆盖

        // 上传文件
        $info = $upload->uploadOne($_FILES['file']);
        if(!$info) {
            $result = array( 'status' => 0, 'msg' => $upload->getError() );
        }else{
            $result['src'] = C('UPLOAD_FIELD_ROOT') . '/' . $info['savepath'] . $info['savename'];
        }
    } else {
        $result = ['status' => 0, 'msg' => '请上传文件'];
    }

    return $result;
}

/**
 * 手机格式验证
 * @param string $mobile 验证的手机号码
 * @return boolean
 */
function isMobile($mobile){
    if ( !empty($mobile) ) {
        if( preg_match("/^1[34578]\d{9}$/", $mobile) ){
            return true;
        }
    }
    return false;
}

/**
 * 返回JSON通一格式
 * by zhaojiping liuniukeji.com
 */
function V($status=-1, $info='', $data=''){
    if ($status == -1) {
        exit('参数调用错误');
    }
    return array('status'=>$status, 'info'=>$info, 'data'=>$data);
}

/**
 * 通用分页处理函数
 * @param Int $count 总条数
 * @param int $page_size 分页大小
 * @return Array  ['page']分页数据  ['limit']查询调用的limit条件
 */
function get_page($count, $page_size=0){
    if ($page_size == 0) $page_size = C('PAGE_SIZE');
    $page = new \Think\Page($count, $page_size);
    $page->setConfig('theme','%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END%');
    $show = $page->show();
    $limit = $page->firstRow.','.$page->listRows;
    return array('page'=>$show,'limit'=>$limit);
}

/**
 * 时间戳格式化
 * @param int $time
 * @return string 格式化后的时间字符串
 */
function time_format($time = NULL,$style='Y-m-d H:i:s'){
    if (empty($time) || $time == 0) {
        return '';
    }
    $time = $time === NULL ? '' : intval($time);
    return date($style, $time);
}
/*--判断充值用户是否存在--*/
function check_user_exist($phone){
    return M("Register")->where(array('tel'=>$phone))->field('id,upper_upper_agent_id,upper_agent_id,agent_id,tel,agent_tel,upper_agent_tel,upper_upper_agent_tel')->find();
}

/*--发放奖金--*/
//id   money  level phone

function send_charge($uid,$moneynum,$level,$tel,$recharge,$phone,$recharge_no,$job_no){

    $update_time = M('register')->where(array('id'=>$uid))->getField('pupdate_time');//获取上一次结算时间
    //var_dump($update_time);die;
    $data['uid'] = $uid;
    $data['remark']= $level;
    $data['moneys'] = $moneynum;
    $data['recharge'] = $recharge;
    $data['tel']    = $tel;
    $data['phone']    = $phone;
    $data['recharge_no']  = $recharge_no;
    $data['job_no'] = $job_no;
    $data['ctime']  = time();
    $data['stime']  = time();
    $s = M('Pbonus')->add($data);
    if($s){


        //如果结算日期为当天日期，则更新昨日佣金
        //判断update_time是否为今天,是就累加，不是就把之前的金额归零
        $time = date('Y-m-d', $data['ctime']);
        $update_time = date('Y-m-d H:i:s',$update_time);

        //判断上一次结算是否为今天 如果是就累加奖金，不是今天清空奖金数据
        if(strpos($update_time,$time) === false)
        {
            //echo 123;die;
            M('register')
                ->where(['id'=>$uid])
                ->save(array(
                    "commission"=>0
                ));

        }
        $datetime['pupdate_time'] = $data['ctime'];


        M('register')->where(['id'=>$uid])->setInc('pcommission', (float)$moneynum);

        M('register')->where(['id'=>$uid])->save($datetime);
        $s2 = M('register')->where(['id'=>$uid])->setInc('commissions', (float)$moneynum);
        //M('register')->where(['id'=>$toUser['id']])->setInc('commission', $commission);
        if($s2){
            return 1;
        }else{
            M('Pbonus')->where(array('id'=>$s))->delete();
            return 3;
        }
    }else{
        return 2;
    }

    function send_commission($mid,$uid,$moneynum,$level,$achievement){
        $lock = M('register')->where(array('id'=>$uid))->getField('lock');
        $update_time = M('register')->where(array('id'=>$uid))->getField('update_time');
        $tel = M('register')->where(array('id'=>$uid))->getField('tel');
        $commission = $moneynum;
        if ($lock)
        {
            // 增加会员的佣金
            $s1=M('register')->where(['id'=>(int)$uid])->setInc('commissions', (float)$commission);

            //如果结算日期为当天日期，则更新昨日佣金
            $date = strtotime(I('date')) > 0 ? date('Y-m-d', strtotime(I('date'))) : date('Y-m-d');

            if($date!=date('Y-m-d',strtotime($update_time)))
            {
                //echo 113;
                M('register')
                    ->where(['id'=>$uid])
                    ->save(array(
                        "commission"=>0
                    ));

            }
            $datetime['update_time'] = date('Y-m-d H:i:s');

            M('register')->where(['id'=>$uid])->setInc('commission', $commission);

            M('register')->where(['id'=>$uid])->save($datetime);

            // 添加工资奖金记录
            $s2=M('bonus')->add([
                'mid' => $mid,
                'tel' => $tel,
                'time' => $achievement['createtime'],
                'TCJE' => $achievement['tcje'],
                'jsmc' => $achievement['jsmc'],
                'stime' => $date . date(' H:i:s'),
                'uid' => $uid,
                'money' => $commission,
                'remark' => $level
            ]);
        }
        if($s1&&$s2){
            return 1234;
        }
    }

}
